package com.allenkerr.dao.impl;

import com.allenkerr.model.Domain;
import com.allenkerr.dao.DomainRepositoryCustom;
import com.mongodb.WriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


/**
 * http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behaviour
 * http://stackoverflow.com/questions/11880924/how-to-add-custom-method-to-spring-data-jpa
 * <p>
 * Impl postfix of the name on it compared to the core dao interface
 * 名称需要注意！！！必须是 DomainRepositoryImpl，而非 DomainRepositoryCustomImpl
 */
public class DomainRepositoryImpl implements DomainRepositoryCustom {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public int updateDomain(String domain, boolean displayAds) {
        Query query = new Query(Criteria.where("domain").is(domain));
        Update update = new Update();
        update.set("displayAds", displayAds);

        WriteResult result = mongoTemplate.updateFirst(query, update, Domain.class);

        if (result != null)
            return result.getN();
        else
            return 0;
    }

    /**
     * 分页查询domain
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Domain> findDomainByPage(int pageNum, int pageSize) {
        Criteria criteria = Criteria.where("displayAds").is(true);                          //查询条件
//        Query query = new Query(criteria).skip((pageNum - 1) * pageSize).limit(pageSize);   //结果集处理
        Query query = Query.query(criteria);
        query.with(new PageRequest(pageNum, pageSize)); //分页
        query.with(new Sort(Sort.Direction.DESC, "id"));    //降序

        List<Domain> domains = mongoTemplate.find(query, Domain.class);     //执行查询

        return domains;
    }
}